package com.zjw.zy.componse.unityui.service;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：zhong.jw
 * @date ：Created in 2023/3/24 10:31
 */
public class DemoSocketServiceViewModel {

    private static final String TAG = "DemoSocketServiceViewModel";
    private final ExecutorService threadPool = Executors.newCachedThreadPool();

    private final Object mSocketLock = new Object();
    private Socket socket;
    private final MutableLiveData<String> replyLiveData = new MutableLiveData<>();

    public LiveData<String> getReplyLiveData() {
        return replyLiveData;
    }

    public void sendServiceMessage(String message) {
        threadPool.execute(() -> {
            synchronized (mSocketLock) {
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                    Log.d(TAG, "sendServiceMessage: write " + message);

                    mSocketLock.notifyAll();
                } catch (Exception e) {
                    Log.e(TAG, "sendServiceMessage: crash" + e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }


    public void connectService() {
        threadPool.execute(() -> {
            synchronized (this) {
                if (socket == null) {
                    socket = new Socket();
                    try {
                        socket.connect(new InetSocketAddress("192.168.133.110", 9999));
                        startInputThread();
                        Log.d(TAG, "connectService: success");
                    } catch (Exception e) {
                        Log.e(TAG, "connectService: failed");
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void startInputThread() {
        threadPool.execute(() -> {
            Log.d(TAG, "startInputThread");
            byte[] bytes = new byte[1024];
            while (true) {
                try {
                    synchronized (mSocketLock) {
                        mSocketLock.wait();
                    }
                    Log.d(TAG, "check message from service : ");
                    InputStream inputStream = socket.getInputStream();
                    if (inputStream.available() == 0) {
                        Log.d(TAG, "none message from service : ");
                        continue;
                    }
                    Log.d(TAG, "has message from service");
                    while (inputStream.read(bytes) != -1) {
                        String s = new String(bytes, StandardCharsets.UTF_8);
                        Log.d(TAG, "read message from service:" + s);
                        replyLiveData.postValue(s);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "startInputThread: ", e);
                    break;
                }
            }
        });
    }
}
